//
//  OAuthViewController.swift
//  CXWeibo
//
//  Created by chenxu on 16/9/19.
//  Copyright © 2016年 陈旭. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {
    // MARK:- 控件属性
    @IBOutlet weak var webView: UIWebView!
    // MARK:- 系统回调方法
    override func viewDidLoad() {
        super.viewDidLoad()
        setUpNavigationBar()
        loadWeb()
    }
}

// MARK:- 设置UI界面
extension OAuthViewController{
    private func setUpNavigationBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "closeItemClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .Plain, target: self, action: "fillItemClick")
    }
    private func loadWeb(){
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_url)"
        guard let url = NSURL(string: urlString) else{
            return
        }
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
    }
}

// MARK:- 事件监听
extension OAuthViewController{
    @objc private func closeItemClick(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func fillItemClick(){
        let jsString = "document.getElementById('userId').value='cxfinancecx@163.com';document.getElementById('passwd').value=''"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
}

// MARK:- UIWebViewDelegate
extension OAuthViewController : UIWebViewDelegate{
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    // 准备开始加载网页
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let url = request.URL else{
            return true
        }
        let urlString = url.absoluteString
        guard urlString.containsString("code=") else{
            return true
        }
        let code = urlString.componentsSeparatedByString("code=").last!
        loadAccessToken(code)
        return false
    }
}

// MARK:- 请求数据
extension OAuthViewController {
    // MARK:- 请求AccessToken
    private func loadAccessToken(code: String){
        NetworkTools.shareInstance.loadAccessToken(code) { (result, error) -> () in
            guard error == nil else{
                CXPrint(error)
                return
            }
            guard let accountDict = result else{
                CXPrint("没有获取授权后的数据")
                return
            }
            let account = UserAccount(dict: accountDict)
            self.requestUserInfo(account)
        }
    }
    
    // MARK:- 请求用户信息
    private func requestUserInfo(account : UserAccount){
        guard let access_token = account.access_token else{
            return
        }
        guard let uid = account.uid else{
            return
        }
        NetworkTools.shareInstance.requestUserInfo(access_token, uid: uid) { (result, error) -> () in
            guard error == nil else{
                CXPrint(error)
                return
            }
            guard let userInfoDict = result else{
                return
            }
            account.screen_name = userInfoDict["screen_name"] as? String
            account.avatar_large = userInfoDict["avatar_large"] as? String
//            CXPrint(account)
            // 将account信息保存到本地
            var accountPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
            accountPath = (accountPath as NSString).stringByAppendingPathComponent("account.plist")
//            CXPrint(accountPath)
            NSKeyedArchiver.archiveRootObject(account, toFile: accountPath)
        }
    }
}
